package com.hzcx.app.simplechat.view;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatButton;

import com.hzcx.app.simplechat.R;

/**
 * 重新发送验证码按钮
 */
public class SendCodeButton extends AppCompatButton {

    private Context context;
    private CountDownTimer countDownTimer;

    public SendCodeButton(Context context) {
        super(context);
        initView(context);
    }

    public SendCodeButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public SendCodeButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        this.context = context;
//        start();
    }

    /**
     * 开始计时
     */
    public void start() {
        //倒计时
        countDownTimer = new CountDownTimer(60000 + 1050, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                sendIng(millisUntilFinished);
            }

            @Override
            public void onFinish() {
                sendFinish();
            }
        }.start();
    }

    /**
     * 正在发送验证码
     *
     * @param millisUntilFinished
     */
    private void sendIng(long millisUntilFinished) {
        setEnabled(false);
        setTextColor(context.getResources().getColor(R.color.color_374765));
        setBackgroundResource(R.drawable.btn_send_code_bg_normal);
        if (millisUntilFinished > 1000) {
            setText("重新获取(" + (millisUntilFinished / 1000 - 1) + "s)");
        }
    }

    /**
     * 发送完毕，可以重新发送
     */
    public void sendFinish() {
        setEnabled(true);
        setTextColor(context.getResources().getColor(R.color.color_white));
        setBackgroundResource(R.drawable.btn_main_blue_confirm_bg_selete);
        setText("重新获取");
    }

    /**
     * 停止发送
     */
    public void stopSend() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        sendFinish();
    }
}
